string.split = function(s, p)
    local rt= {}
    string.gsub(s, '[^'..p..']+', function(w) table.insert(rt, w) end )
    return rt
end

local sessionComputerSetKeyPrefix = KEYS[1]..':'
local computerSessionSetKeyPrefix = KEYS[2]..':'
local onlineZSetKeyPrefix = KEYS[3]
local sessionKey = KEYS[4]
local deviceInstancePrefix = KEYS[5]
local cuids = ARGV
local setkey = sessionComputerSetKeyPrefix..sessionKey
local result
local disconnect
local connectCount
local tmp

local exist_device
local deviceinstance

--查找当前用户已经绑定的上位机
local exist = redis.call("smembers",setkey)

--删除设备与用户的绑定关联
if next(exist) ~=nil then
    for _, device in ipairs(exist) do
        redis.call("srem",computerSessionSetKeyPrefix..device,sessionKey)
    end
end
--删除用户与设备的绑定关联
redis.call("del",setkey)

--重新添加联系信息
if next(cuids) ~=nil then
    for _, s in ipairs(cuids) do
        exist_device = false
        deviceinstance = redis.call("smembers",deviceInstancePrefix..':'..s)
        if next(deviceinstance) ~=nil then
            exist_device=true
        end
        if exist_device then
            redis.call("sadd",setkey,s)
            redis.call("sadd",computerSessionSetKeyPrefix..s,sessionKey)
--        else
--            if result then
--                result = result..','..s
--            else
--                result = s
--            end
        end
    end
end

--不在线的上位机
if not result then
    result = ''
end

--检查上位机是否还有用户绑定，如果没有绑定，则需要发消息给上位机，通知不用再发数据
--if next(exist) ~=nil then
--    for _, cuid in ipairs(exist) do
--        connectCount = tonumber(redis.call("SCARD",computerSessionSetKeyPrefix..cuid))
--        if(connectCount <= 0) then
--            tmp = redis.call("get",cuid)
--            if  tmp then
--                connectCount = connectCount + 1
--            end
--        end
--        if(connectCount <= 0) then
--            if disconnect then
--                disconnect = disconnect..','..cuid
--            else
--                disconnect = cuid
--            end
--        end
--    end
--end
----没有用户绑定的上位机
if not disconnect then
    disconnect = ''
end

return result..':'..disconnect